//
//  CorrectModule.m
//  DocCorrect
//
//  Created by zhangyin on 2023/10/14.
//

#import "CorrectModule.h"

#import <VisionKit/VisionKit.h>
#import <UIView+Toast.h>

@interface CorrectModule()<VNDocumentCameraViewControllerDelegate>

@property(nonatomic,strong)UniModuleKeepAliveCallback resultCallback;
@property(nonatomic,assign)NSUInteger maxCount;

@end

@implementation CorrectModule

// 通过宏 UNI_EXPORT_METHOD 将异步方法暴露给 js 端
UNI_EXPORT_METHOD(@selector(detect:callback:))

- (void) detect: (NSDictionary *)options callback: (UniModuleKeepAliveCallback)callback {
    NSLog(@"【options】：%@", options);
    
    NSString* mc = [options objectForKey: @"maxCount"];
    if(mc) {
        self.maxCount = [mc integerValue];
    }
    
    if (callback) {
        self.resultCallback = callback;
        [self startDetect];
        
        //        NSArray *key = @[@"code", @"data"];
        //        NSArray *object = @[@"success", @"zhangyin"];
        //        NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:object forKeys:key];
        //        callback(dictionary, NO);
        
    }
}

/**
 * UUID 随机码
 */
- (NSString *)uuidString {
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref = CFUUIDCreateString(NULL, uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];
    CFRelease(uuid_ref);
    CFRelease(uuid_string_ref);
    return [uuid lowercaseString];
}

- (void)saveImage:(UIImage *)image fileUrl:(NSURL *) fileUrl {
    [UIImagePNGRepresentation(image) writeToURL:fileUrl atomically:YES];
    
    BOOL result = [UIImagePNGRepresentation(image) writeToURL:fileUrl atomically:YES];
    
    if(result == YES) {
        NSLog(@"%@ 保存成功",fileUrl);
    } else {
        NSLog(@"%@ 保存失败",fileUrl);
    }
    
}

/**
 * 检测结束回调
 */
- (void)documentCameraViewController:(VNDocumentCameraViewController *)controller didFinishWithScan:(VNDocumentCameraScan *)scan API_AVAILABLE(ios(13)){
    NSUInteger len = [scan pageCount];
    
    if(self.maxCount > 0 && len > self.maxCount) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message: [NSString stringWithFormat: @"最大数量为%lu，请删减图片后重试，存储和拍照将暂时禁用", self.maxCount] preferredStyle: UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil ]];
        
        [controller presentViewController:alertVC animated:YES completion:nil];
        return;
    }
    
    [self closeDocumentCameraView];
    
    // 处理
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *tempDirUrl = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
        
        NSMutableArray<NSString *> *list = @[].mutableCopy;
        for(int i = 0; i < len; i++) {
            UIImage* item = [scan imageOfPageAtIndex:i];
            
            NSString *fileName = [NSString stringWithFormat:@"vision_kit_%@.png",[self uuidString]];
            NSURL *fileUrl = [tempDirUrl URLByAppendingPathComponent:fileName];
            [self saveImage:item fileUrl:fileUrl];
            
            [list addObject:fileUrl.absoluteString];
            
            NSLog(@"共计%lu，已完成%d", len, i + 1);
        }
        
        // 倒置数组
        /* NSArray<NSString *> *reversedList = [[list reverseObjectEnumerator] allObjects]; */
        
        NSArray *key = @[@"code", @"data"];
        NSArray *object = @[@"success", list];
        NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:object forKeys:key];
        
        self.resultCallback(dictionary, NO);
        
        //
    });
    
    
    //
}

/**
 * 检测取消
 */
- (void)documentCameraViewControllerDidCancel:(VNDocumentCameraViewController *)controller API_AVAILABLE(ios(13.0)){
    
    [self closeDocumentCameraView];
}

/**
 * 关闭检测
 */
- (void)closeDocumentCameraView{
    UIWindow *window = [[UIApplication sharedApplication]windows].lastObject;
    [window.rootViewController dismissViewControllerAnimated:YES completion:nil];
}

/**
 * 检测
 */
- (void) startDetect{
    UIWindow *window = [[UIApplication sharedApplication]windows].lastObject;
    
    if(@available(iOS 13, *)) {
        if(!VNDocumentCameraViewController.isSupported) {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前设备不支持，请检查设备摄像头" preferredStyle: UIAlertControllerStyleAlert];
            [alertVC addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil ]];
            
            [window.rootViewController presentViewController:alertVC animated:YES completion:nil];
            return;
        }
        
        VNDocumentCameraViewController *dcVc = [[VNDocumentCameraViewController alloc] init];
        
        dcVc.delegate = self;
        
        [window.rootViewController presentViewController:dcVc animated:YES completion:nil];
        
        //
    } else {
        [window.rootViewController.view makeToast:@"只支持ios 13.0以上系统"];
    }
    
    
    //
}

@end
